package org.study.singleton;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于内部类的单例模式写法示例
 *
 * @author Administrator
 */
public class MyExceptionManager {
    public static void main(String[] args) {
        MyExceptionManager instance = MyExceptionManager.getInstance();
        instance.putException("test", new Exception());
        Exception test = instance.getException("test");
        System.out.println(test);
    }

    private static ConcurrentHashMap<String, Exception> concurrentHashMap;

    private MyExceptionManager() {
        concurrentHashMap = new ConcurrentHashMap<>();
    }

    private static class MyExceptionManagerInstance {
        private static final MyExceptionManager instance = new MyExceptionManager();
    }

    public static MyExceptionManager getInstance() {
        return MyExceptionManagerInstance.instance;
    }

    public synchronized void putException(String key, Exception exception) {
        concurrentHashMap.put(key, exception);
    }

    public synchronized Exception getException(String key) {
        if (concurrentHashMap.containsKey(key)) {
            return concurrentHashMap.get(key);
        }
        return null;
    }
}
